using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.NetworkInformation;
using BanZuiCloudControlAgent.Core.Tasks.Base;
using BanZuiCloudControlAgent.Core.Tasks.Enums;
using BanZuiCloudControlAgent.Core.Tasks.Models;
using BanZuiCloudControlAgent.Core.Tasks.Queue;
using BanZuiCloudControlAgent.Utils.Common;

namespace BanZuiCloudControlAgent.Core.Mqtt.Models
{
    /// <summary>
    /// 状态上报消息负载模型
    /// </summary>
    public class StatusReportPayloadModel
    {
        /// <summary>
        /// 设备名称
        /// </summary>
        [JsonProperty("deviceName")]
        public string DeviceName { get; set; }

        /// <summary>
        /// MAC地址
        /// </summary>
        [JsonProperty("macAddress")]
        public string MacAddress { get; set; }

        /// <summary>
        /// IP地址
        /// </summary>
        [JsonProperty("ipAddress")]
        public string IpAddress { get; set; }

        /// <summary>
        /// 系统信息
        /// </summary>
        [JsonProperty("systemInfo")]
        public string SystemInfo { get; set; }

        /// <summary>
        /// CPU信息
        /// </summary>
        [JsonProperty("cpuInfo")]
        public string CpuInfo { get; set; }

        /// <summary>
        /// 内存大小(MB)
        /// </summary>
        [JsonProperty("memorySize")]
        public int MemorySize { get; set; }

        /// <summary>
        /// 磁盘大小(GB)
        /// </summary>
        [JsonProperty("diskSize")]
        public int DiskSize { get; set; }

        /// <summary>
        /// 客户端版本
        /// </summary>
        [JsonProperty("clientVersion")]
        public string ClientVersion { get; set; }

        /// <summary>
        /// 已使用内存(MB)
        /// </summary>
        [JsonProperty("memoryUsed")]
        public int MemoryUsed { get; set; }

        /// <summary>
        /// 内存使用率(%)
        /// </summary>
        [JsonProperty("memoryUsage")]
        public double MemoryUsage { get; set; }

        /// <summary>
        /// CPU使用率(%)
        /// </summary>
        [JsonProperty("cpuUsage")]
        public double CpuUsage { get; set; }

        /// <summary>
        /// 已使用磁盘(GB)
        /// </summary>
        [JsonProperty("diskUsed")]
        public int DiskUsed { get; set; }

        /// <summary>
        /// 磁盘使用率(%)
        /// </summary>
        [JsonProperty("diskUsage")]
        public double DiskUsage { get; set; }

        /// <summary>
        /// 在线QQ数量
        /// </summary>
        [JsonProperty("onlineQQCount")]
        public int OnlineQQCount { get; set; }

        /// <summary>
        /// 网络状态
        /// </summary>
        [JsonProperty("networkStatus")]
        public string NetworkStatus { get; set; }

        /// <summary>
        /// 是否首次连接
        /// </summary>
        [JsonProperty("isFirstConnect")]
        public bool IsFirstConnect { get; set; }

        /// <summary>
        /// 是否心跳消息
        /// </summary>
        [JsonProperty("isHeartbeat")]
        public bool IsHeartbeat { get; set; }
        
        /// <summary>
        /// 当前任务状态列表
        /// </summary>
        [JsonProperty("taskList")]
        public List<TaskStatusInfo> TaskStatusList { get; set; } = new List<TaskStatusInfo>();
        

        /// <summary>
        /// 运行中任务数量
        /// </summary>
        [JsonProperty("runningTaskCount")]
        public int RunningTaskCount { get; set; }
    }

    /// <summary>
    /// 状态上报消息模型
    /// </summary>
    public class StatusReportModel : BaseMessageModel
    {
        /// <summary>
        /// 构造函数
        /// </summary>
        public StatusReportModel() : base()
        {
            MessageType = MessageTypeConstants.STATUS_REPORT;
        }

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="deviceCode">设备码</param>
        /// <param name="payload">状态上报负载</param>
        public StatusReportModel(string deviceCode, StatusReportPayloadModel payload) 
            : base(MessageTypeConstants.STATUS_REPORT, deviceCode, payload)
        {
        }

        /// <summary>
        /// 获取状态上报负载
        /// </summary>
        /// <returns>状态上报负载</returns>
        public StatusReportPayloadModel GetPayload()
        {
            return Payload as StatusReportPayloadModel;
        }
        
        /// <summary>
        /// 添加任务状态信息到状态上报
        /// </summary>
        /// <param name="taskQueue">任务队列</param>
        public void AddTaskStatus(TaskQueue taskQueue)
        {
            if (taskQueue == null || !(Payload is StatusReportPayloadModel payload))
                return;
            
            try
            {
                // 获取所有任务
                var allTasks = taskQueue.GetAllTasks();
                
                // 获取运行中的任务
                var runningTasks = allTasks.Where(t => t.Status == TaskState.Running).ToList();
                
                // 设置运行中任务数量
                payload.RunningTaskCount = runningTasks.Count;
                
                // 添加任务状态信息
                foreach (var task in allTasks)
                {
                    var taskStatusInfo = TaskStatusInfo.FromTask(task);
                    if (taskStatusInfo != null)
                    {
                        payload.TaskStatusList.Add(taskStatusInfo);
                    }
                }
            }
            catch (Exception ex)
            {
                // 忽略异常，确保状态上报不会因为获取任务状态失败而中断
                System.Diagnostics.Debug.WriteLine($"获取任务状态信息失败: {ex.Message}");
            }
        }
        
        /// <summary>
        /// 创建状态上报消息
        /// </summary>
        /// <param name="deviceCode">设备码</param>
        /// <param name="deviceName">设备名称</param>
        /// <param name="isHeartbeat">是否为心跳消息</param>
        /// <param name="isFirstConnect">是否为首次连接</param>
        /// <param name="taskQueue">任务队列，用于获取任务状态</param>
        /// <returns>状态上报消息</returns>
        public static StatusReportModel CreateStatusReport(
            string deviceCode, 
            string deviceName, 
            bool isHeartbeat = true, 
            bool isFirstConnect = false, 
            TaskQueue taskQueue = null)
        {
            // 创建状态上报负载
            var payload = new StatusReportPayloadModel
            {
                DeviceName = deviceName,
                IsHeartbeat = isHeartbeat,
                IsFirstConnect = isFirstConnect,
                NetworkStatus = isFirstConnect ? "CONNECTED" : null,
                MacAddress = GetMacAddress(),
                IpAddress = GetIpAddress(),
                ClientVersion = GetClientVersion()
            };
            
            // 如果是首次连接或非心跳消息，添加完整的系统信息
            if (isFirstConnect || !isHeartbeat)
            {
                payload.SystemInfo = GetSystemInfo();
                payload.CpuInfo = GetCpuInfo();
                payload.MemorySize = GetTotalMemory();
                payload.DiskSize = GetTotalDiskSpace();
                payload.OnlineQQCount = GetOnlineQQCount();
            }
            
            // 这些信息每次都需要更新
            payload.CpuUsage = GetCpuUsage();
            payload.MemoryUsed = GetUsedMemory();
            payload.MemoryUsage = GetMemoryUsage();
            payload.DiskUsed = GetUsedDiskSpace();
            payload.DiskUsage = GetDiskUsage();
            
            // 创建状态上报消息
            var statusReport = new StatusReportModel(deviceCode, payload);
            
            // 添加任务状态信息
            if (taskQueue != null)
            {
                statusReport.AddTaskStatus(taskQueue);
            }
            
            return statusReport;
        }
        
        #region 辅助方法
        
        private static string GetMacAddress()
        {
            try
            {
                var networkAdapters = SystemInfo.GetNetworkAdapterInfo();
                if (networkAdapters != null && networkAdapters.Count > 0)
                {
                    // 获取第一个已连接的网络适配器的MAC地址
                    var connectedAdapter = networkAdapters.FirstOrDefault(a => a.Status == "Up");
                    if (connectedAdapter != null && !string.IsNullOrEmpty(connectedAdapter.MacAddress))
                    {
                        return connectedAdapter.MacAddress;
                    }
                }
                return "00:00:00:00:00:00";
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"获取MAC地址失败: {ex.Message}");
                return "00:00:00:00:00:00";
            }
        }
        
        private static string GetIpAddress()
        {
            try
            {
                return SystemInfo.GetLocalIpAddress();
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"获取IP地址失败: {ex.Message}");
                return "127.0.0.1";
            }
        }
        
        private static string GetClientVersion()
        {
            try
            {
                return AppConstants.AppVersion;
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"获取客户端版本失败: {ex.Message}");
                return "1.0.0";
            }
        }
        
        private static string GetSystemInfo()
        {
            try
            {
                return SystemInfo.GetOSVersion();
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"获取系统信息失败: {ex.Message}");
                return "Unknown OS";
            }
        }
        
        private static string GetCpuInfo()
        {
            try
            {
                return SystemInfo.GetCpuInfo();
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"获取CPU信息失败: {ex.Message}");
                return "Unknown CPU";
            }
        }
        
        private static int GetTotalMemory()
        {
            try
            {
                var memoryMetrics = SystemInfo.GetMemoryUsage();
                return (int)(memoryMetrics.Total / (1024 * 1024)); // 转换为MB
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"获取总内存失败: {ex.Message}");
                return 8192; // 默认8GB
            }
        }
        
        private static int GetTotalDiskSpace()
        {
            try
            {
                var diskInfo = SystemInfo.GetDiskInfo();
                if (diskInfo != null && diskInfo.Count > 0)
                {
                    // 获取所有磁盘的总空间
                    return (int)diskInfo.Sum(d => d.TotalSizeGB);
                }
                return 512; // 默认512GB
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"获取总磁盘空间失败: {ex.Message}");
                return 512; // 默认512GB
            }
        }
        
        private static int GetUsedMemory()
        {
            try
            {
                var memoryMetrics = SystemInfo.GetMemoryUsage();
                return (int)(memoryMetrics.Used / (1024 * 1024)); // 转换为MB
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"获取已使用内存失败: {ex.Message}");
                return 4096; // 默认4GB
            }
        }
        
        private static double GetMemoryUsage()
        {
            try
            {
                var memoryMetrics = SystemInfo.GetMemoryUsage();
                return memoryMetrics.UsagePercentage;
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"获取内存使用率失败: {ex.Message}");
                return 50.0; // 默认50%
            }
        }
        
        private static double GetCpuUsage()
        {
            try
            {
                return SystemInfo.GetCpuUsage();
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"获取CPU使用率失败: {ex.Message}");
                return 25.5; // 默认25.5%
            }
        }
        
        private static int GetUsedDiskSpace()
        {
            try
            {
                var diskInfo = SystemInfo.GetDiskInfo();
                if (diskInfo != null && diskInfo.Count > 0)
                {
                    // 获取所有磁盘的已使用空间
                    return (int)diskInfo.Sum(d => d.UsedSpaceGB);
                }
                return 256; // 默认256GB
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"获取已使用磁盘空间失败: {ex.Message}");
                return 256; // 默认256GB
            }
        }
        
        private static double GetDiskUsage()
        {
            try
            {
                var diskInfo = SystemInfo.GetDiskInfo();
                if (diskInfo != null && diskInfo.Count > 0)
                {
                    // 计算所有磁盘的平均使用率
                    return diskInfo.Average(d => d.UsagePercentage);
                }
                return 50.0; // 默认50%
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"获取磁盘使用率失败: {ex.Message}");
                return 50.0; // 默认50%
            }
        }
        
        private static int GetOnlineQQCount()
        {
            // TODO: 实现获取在线QQ数量的方法，需要与QQ管理器集成
            try
            {
                // 这里应该调用QQ管理器获取在线QQ数量
                // 例如: return QQManager.Instance.GetOnlineQQCount();
                return 0;
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"获取在线QQ数量失败: {ex.Message}");
                return 0;
            }
        }
        
        #endregion
    }
} 